package org.proteored.miapeapi.xml.pride.adapter;

import java.util.List;

import org.apache.log4j.Logger;
import org.proteored.miapeapi.cv.ControlVocabularyManager;
import org.proteored.miapeapi.cv.SampleInformation;
import org.proteored.miapeapi.interfaces.Adapter;
import org.proteored.miapeapi.interfaces.ms.MSAdditionalInformation;
import org.proteored.miapeapi.interfaces.ms.MSContact;
import org.proteored.miapeapi.interfaces.ms.MiapeMSDocument;
import org.proteored.miapeapi.interfaces.ms.ResultingData;
import org.proteored.miapeapi.xml.pride.autogenerated.AdminType;
import org.proteored.miapeapi.xml.pride.autogenerated.ObjectFactory;
import org.proteored.miapeapi.xml.pride.util.PrideControlVocabularyXmlFactory;

public class AdminAdapter implements Adapter<AdminType> {
	private static Logger log = Logger.getLogger("log4j.logger.org.proteored");
	private final ObjectFactory factory;
	private final ControlVocabularyManager cvManager;
	private final MiapeMSDocument miapeMS;
	private final PrideControlVocabularyXmlFactory prideCvUtil;

	public AdminAdapter(ObjectFactory factory, ControlVocabularyManager cvManager,
			MiapeMSDocument mergedMiapeMS) {
		this.miapeMS = mergedMiapeMS;
		this.prideCvUtil = new PrideControlVocabularyXmlFactory(factory, cvManager);
		this.factory = factory;
		this.cvManager = cvManager;
	}

	@Override
	public AdminType adapt() {
		MSContact msiContact = null;
		MSContact msContact = null;

		log.info("createAdmin");
		AdminType admin = factory.createAdminType();

		// mandatories
		String sampleName = getSampleName();
		log.info("Sample name = " + sampleName);
		admin.setSampleName(sampleName);

		if (miapeMS != null) {
			msContact = miapeMS.getContact();
			if (msContact != null)
				admin.getContact()
						.add(new PersonTypeAdapter(factory, cvManager, msContact).adapt());
		}

		if (msiContact == null && msContact == null) {
			admin.getContact().add(new PersonTypeAdapter(factory, cvManager, null).adapt());
		}

		// not mandatories

		// TODO extract it from MIAPE?

		admin.setSampleDescription(new SampleDescriptionAdapter(factory, cvManager, miapeMS)
				.adapt());
		if (miapeMS != null) {
			List<ResultingData> resultingDatas = miapeMS.getResultingDatas();
			if (resultingDatas != null)
				admin.setSourceFile(new SourceFileTypeAdapter(factory, resultingDatas).adapt());
		}
		return admin;
	}

	private String getSampleName() {
		if (miapeMS != null) {
			List<MSAdditionalInformation> additionalInformations = miapeMS
					.getAdditionalInformations();
			if (additionalInformations != null) {
				for (MSAdditionalInformation addInfo : additionalInformations) {
					if (addInfo.getName().equalsIgnoreCase(
							SampleInformation.getInstance(cvManager).getSampleBatchTerm()
									.getPreferredName()))
						return addInfo.getValue();
				}
			}
		}
		return "Unknown";
	}

}
